package com.loong.framework.utils;

import com.google.common.base.Strings;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * @email 473496220@qq.com
 * @author:Ten.X
 * @date: 2022/10/11
 * @time: 17:20
 */
public class CommonUtil {

  /**
   * 判断是否为空
   *
   * @param obj
   * @return
   */
  public static boolean isNullOrEmpty(Object obj) {
    if (obj == null) {
      return true;
    } else if (obj instanceof String) {
      return Strings.isNullOrEmpty((String) obj);
    } else if (obj instanceof Collection) {
      return ((Collection<?>) obj).isEmpty();
    } else if (obj instanceof StringBuilder) {
      return ((StringBuilder) obj).isEmpty();
    } else if (obj instanceof CharSequence) {
      return ((CharSequence) obj).isEmpty();
    } else if (obj.getClass().isArray()) {
      return java.lang.reflect.Array.getLength(obj) == 0;
    } else if (obj instanceof Map) {
      return ((Map<?, ?>) obj).isEmpty();
    } else if (obj instanceof Optional) {
      return ((Optional<?>) obj).isEmpty();
    }
    return false;
  }

  /**
   * 判断是否不为空
   *
   * @param obj
   * @return
   */
  public static boolean notNullOrEmpty(Object obj) {
    return !isNullOrEmpty(obj);
  }

  /**
   * 安全的equal方法
   *
   * @param str1
   * @param str2
   * @return
   */
  public static boolean safeEqual(String str1, String str2) {
    if (str1 == null && str2 == null) {
      return true;
    }
    if (str1 == null || str2 == null) {
      return false;
    }

    if (str1.length() != str2.length()) {
      return false;
    }

    boolean result = true;
    for (int i = 0; i < str1.length(); i++) {
      char c1 = str1.charAt(i);
      char c2 = str2.charAt(i);
      result &= (c1 == c2);
    }
    return result;
  }
}
